﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Text;
using System.IO;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Threading;

namespace PhoneClassLibraryJSON {
    public class SendRequest {

        
        Action<List<IResult>> myActionResults;   

        Action<IConnect> myActionConnection;                   

        //1er étape de la connection : on s'authentifie
        public void getConnection( string websiteURL_Authentification, Action<IConnect> ac ) {
            WebClient c = new WebClient();

            myActionConnection = ac;

            c.DownloadStringCompleted += new DownloadStringCompletedEventHandler( c_DownloadStringCompleted );

            c.DownloadStringAsync( new Uri( websiteURL_Authentification ) );
        }

       //2em etape de la connection, on recupère les items
       public void getResults( string websiteURL_getResult, Action<List<IResult>> ac ) {
            WebClient c = new WebClient();

            myActionResults = ac;

            c.DownloadStringCompleted += new DownloadStringCompletedEventHandler( c_DownloadStringCompleted );

            c.DownloadStringAsync( new Uri( websiteURL_getResult ) );
        }


        //eventHandler
        void c_DownloadStringCompleted( object sender, DownloadStringCompletedEventArgs e ) {
            try {
                string s = e.Result;
                JObject o = JObject.Parse( s );

                if (o["connect"] != null) {      // 1er cas : réponse à l'authentification
                    IConnect connec = Connection.JSon2Connect( o );

                    if (myActionConnection != null) {
                        myActionConnection( connec );
                    }
                } else {                         // 2em cas : réponse à la demande de données
                    List<IResult> LRes = Result.json2Result( o );
                    if (myActionConnection != null) {
                        myActionResults( LRes );
                    }
                }
            } catch (Exception exc) {
                Console.WriteLine( exc.StackTrace );
            }
        } 
    }
}
